// $Id$
package lime.xquery.widget;

import java.util.ArrayList;
import java.util.List;

import lime.common.DOMUtils;
import lime.common.UIUtils;
import lime.xquery.provider.DocumentContentProvider;
import lime.xquery.provider.DocumentLabelProvider;
import lime.xquery.provider.XmlSorter;

import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableColumn;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XQueryDataResult extends Composite {

	public XQueryDataResult(Composite parent, int style) {
		super(parent, style);
		init();
	}

	private void init() {
		this.setLayout(new FillLayout());
	}

	public void update(String text) {

		Document doc = null;
		try {
			doc = DOMUtils.parse(text);
		} catch (Exception e) {
			e.printStackTrace();
		}

		UIUtils.clear(this);

		final TableViewer viewer = new TableViewer(this, SWT.BORDER | SWT.FULL_SELECTION);

		// Add column headers to the table
		for (final String header : getColumnNames(doc)) {
			TableViewerColumn column = new TableViewerColumn(viewer, SWT.NONE);
			column.getColumn().setText(header);
			column.getColumn().addSelectionListener(new SelectionAdapter() {
				public void widgetSelected(SelectionEvent e) {
					viewer.setSorter(new XmlSorter(header));
					viewer.refresh();
				}
			});
		}

		TableLayout layout = new TableLayout();
		viewer.getTable().setLayout(layout);
		viewer.getTable().setLinesVisible(true);
		viewer.getTable().setHeaderVisible(true);

		viewer.setLabelProvider(new DocumentLabelProvider());
		viewer.setContentProvider(new DocumentContentProvider());

		viewer.setInput(doc);

		// Make sure the columns take up as much space as needed, but not more.
		viewer.getTable().pack();
		for (TableColumn column : viewer.getTable().getColumns()) {
			column.pack();
		}

		this.layout();

	}

	private List<String> getColumnNames(Document doc) {

		List<String> columnNames = new ArrayList<String>();

		Element firstRow = null;
		NodeList nodes = doc.getDocumentElement().getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				firstRow = (Element) node;
				break;
			}
		}

		if (firstRow != null) {
			NodeList headers = firstRow.getChildNodes();
			for (int i = 0; i < headers.getLength(); i++) {
				Node node = headers.item(i);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					columnNames.add(node.getNodeName());
				}
			}
		}

		return columnNames;
	}

}
